
#include <view/Fonte.h>

Fonte::Fonte(std::string strNomeDaFonte, int tamanho, int cor)
    : m_tamanho(tamanho)
{
    HDC hdcMem = ::CreateCompatibleDC(::GetDC(HWND_DESKTOP));
    ReleaseDC(NULL, GetDC(NULL));
    
    HFONT hFont = ::CreateFont(tamanho, 0, 0, 0, FW_NORMAL, 0, 0, 0, ANSI_CHARSET,
                               OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
                               DEFAULT_PITCH | FF_DONTCARE, strNomeDaFonte.c_str());
    
    ::SelectObject(hdcMem, hFont);
    
    ABC metrica[256];
    
    if(::GetCharABCWidths(hdcMem, 0, 255, metrica))
        for(int i=0; i<256; i++)
            larguraDoChar[i] = (metrica[i].abcA + metrica[i].abcB + metrica[i].abcC);
            
    char ch[256];
    for(int i=0; i<256; i++)
        ch[i] = i;
    
    for(int i=0; i<256; i++)
    {
        im[i] = new Imagem(larguraDoChar[i], tamanho);
        
        char szText[3];
#ifdef _MSC_VER
        sprintf_s(szText,3,"%c",ch[i]);
#else
        sprintf(szText,"%c",ch[i]);
#endif
        
        RECT rect={0,0,larguraDoChar[i],tamanho};

        HBITMAP hBitmap= ::CreateCompatibleBitmap(hdcMem,
                                                  rect.right-rect.left,
                                                  rect.bottom-rect.top);

        ::SelectObject(hdcMem, hBitmap);

        ::FillRect(hdcMem,&rect,(HBRUSH)::GetStockObject(WHITE_BRUSH));
        
        ::DrawText(hdcMem,szText,1,&rect, 
         DT_LEFT|DT_TOP|DT_SINGLELINE|DT_NOPREFIX);

        for(int j=0; j<im[i]->Largura(); j++)
            for(int k=0; k<im[i]->Altura(); k++)
            {
                COLORREF rgbColor = ::GetPixel(hdcMem, j, k);
                
                if(GetRValue(rgbColor))
                    (*(im[i]))[j][k] = RGBA(0,0,0,0);
                else
                    (*(im[i]))[j][k] = cor;
            }
        
        ::DeleteObject(hBitmap);
    }
    
    ::DeleteDC(hdcMem);
}

Fonte::~Fonte()
{
    for(int i=0; i<256; i++)
        delete im[i];
}


Imagem* Fonte::operator[](unsigned char i)
{
    return im[i];
}

int Fonte::LarguraDoChar(unsigned char i)
{
    return larguraDoChar[i];
}


/*
int Texto::LarguraDoTexto(char* sz, int n)
{
    ABC metrica[256];
    
    if(GetCharABCWidths(GetDC(m_hwnd), 0, 255, metrica))
    {
        int cont = 0;
        
        for(int i=0; i<n; i++)
            cont += (metrica[sz[i]].abcA + metrica[sz[i]].abcB + metrica[sz[i]].abcC);
        
        return cont;
    }
}
*/
